﻿app.factory('MessagesService', ['$http', function ($http) {
    var messages = [];
    var getMessages = function (callback) {
        if (messages.length > 0) {
            callback(messages);
        }
        else {
            $http.get('https://nicksmessages.firebaseio.com/messages/.json')
            .success(function (data) {
                messages.length = 0;
                for (var m in data) {
                    data[m].id = m;
                    messages.push(data[m]);
                }
                callback(messages);
            });
        }
    }

    var getMessage = function (id, callback) {
        var message;

        //Try to locate the message in the array first
        for (var i in messages) {
            if (messages[i].id === id) {
                message = messages[i];
                break;
            }
        }

        //If the message is found in the array, return it.  If not, get it from Firebase
        if (message) {
            callback(message);
        }
        else {
            $http.get('https://nicksmessages.firebaseio.com/messages/' + id + '.json')
            .success(function (data) {
                messages.push(data);
                callback(data);
            });
        }
    };

    var createMessage = function (message, callback) {
        message.time = new Date();
        $http.post('https://nicksmessages.firebaseio.com/messages/.json', message)
        .success(function (data) {
            message.id = data.name;
            messages.push(message);
            callback(data.name);
        });
    }

    return {
        getMessages: getMessages,
        getMessage: getMessage,
        createMessage: createMessage
    };
}])